
import { CheckAns } from "./CheckAns";

namespace LeetCode1423MaxScore {

    function maxScore(cardPoints: number[], k: number): number {
        if (!cardPoints || k == NaN || cardPoints.length < k) return 0;
        // 只能从首尾取共计K张牌，并获取最大点数之和；即：从数组中取连续s.length-k张牌，求和的最小点数，总点数-最小和点数 = 需要的答案
        const length: number = cardPoints.length;
        const windowLen: number = length - k;
        // init some values
        let tempV: number = 0;
        let sumPts: number = 0;
        cardPoints.forEach((v: number, i: number) => {
            sumPts += v;
            if (i == windowLen - 1)
                tempV = sumPts;
        });
        let minV = tempV;
        // 循环遍历
        for (let i = windowLen; i < length; i++) {
            tempV += cardPoints[i] - cardPoints[i - windowLen];
            if (tempV < minV)
                minV = tempV;
        }
        return sumPts - minV;
    };

    // test
    const testData: { cardPoints: number[], k: number, ans: number }[] = [
        { cardPoints: [1, 2, 3, 4, 5, 6, 1], k: 3, ans: 12 },
        { cardPoints: [2, 2, 2], k: 2, ans: 4 },
        { cardPoints: [9, 7, 7, 9, 7, 7, 9], k: 7, ans: 55 },
        { cardPoints: [1, 1000, 1], k: 1, ans: 1 },
        { cardPoints: [1, 79, 80, 1, 1, 1, 200, 1], k: 3, ans: 202 }
    ];
    for (const data of testData) {
        const ans = maxScore(data.cardPoints, data.k);
        CheckAns(data, ans);
    }
}